using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour 
{
	GameObject m_gMainBall;
	public bool m_bFollowing = false;
	public bool m_bFollowingTopDown = false;
	
	public float m_fHeight = 10.0f;
public 	float m_fDistance = 15.0f;
	
	public float m_fRotationSpeed = 2.0f;
	public float m_fTranslationSpeed = 2.0f;
	
	// Use this for initialization
	void Start () 
	{
	if(m_bFollowing)
		{
		CheckBall();
		
		}
	}
	void CheckBall()
	{
		if(m_gMainBall)
			return;
		
		foreach (GameObject g in GameObject.FindGameObjectsWithTag("Ball"))
		{
			if(g.GetComponent<BallController>().IsMain)
			{
				m_gMainBall = g;
				
			}
		 
		}
	}
	
	// Update is called once per frame
	void Update () 
	{
	if(m_bFollowing || m_bFollowingTopDown)
			CheckBall();
	}
	void LateUpdate()
	{
		if(m_bFollowing || m_bFollowingTopDown)
		{
		if(!m_gMainBall)
			return;
		
		float _TargetRotationAngle = m_gMainBall.transform.rotation.eulerAngles.y;
		float _TargetHeight = m_gMainBall.transform.position.y + m_fHeight;
		
		float _CurrentRotationAngle = transform.rotation.eulerAngles.y;
		float _CurrentHeight = transform.position.y;
		
		//now calculate the next position to move to
		
		_CurrentRotationAngle = Mathf.LerpAngle(_CurrentRotationAngle, _TargetRotationAngle, Time.deltaTime * m_fRotationSpeed);
		_CurrentHeight = Mathf.Lerp(_CurrentHeight, _TargetHeight, Time.deltaTime * m_fTranslationSpeed);
		
		Quaternion _CurrentRotation = Quaternion.Euler(0,_CurrentRotationAngle, 0);
		transform.position = m_gMainBall.transform.position;
			if(m_bFollowing)
		transform.position -= (_CurrentRotation * Vector3.forward * m_fDistance);
		else if(m_bFollowingTopDown)
		transform.position -= (_CurrentRotation * transform.forward * m_fDistance);
			
		transform.position = new Vector3(transform.position.x, _CurrentHeight, transform.position.z);
		
		transform.LookAt(m_gMainBall.transform);
		
		}		
	}
}
